package com.example.demo.zk;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * Created by alva on 18/6/13.
 */
public class DistributedRedisLock {
    private static RedissonClient redisson = RedissonManager.getRedisson();

    public static void acquire(String lockName) throws InterruptedException{
        String key =  lockName;
        RLock mylock = redisson.getLock(key);
        if(mylock.tryLock(7000, 10000,TimeUnit.MILLISECONDS)){
            System.err.println("======get lock======"+Thread.currentThread().getName());
            Thread.sleep(5000); //获得锁之后可以进行相应的处理
        }else{
            System.err.println("get lock failed==="+Thread.currentThread().getName());
        }

    }

    public static void release(String lockName){
        String key =lockName;
        RLock mylock = redisson.getLock(key);
        if(mylock != null){
            mylock.unlock();
            System.err.println("======unlock======"+Thread.currentThread().getName());
        }

//        System.err.println("======unlock======"+Thread.currentThread().getName());
    }

    public static void main(String[] args) throws InterruptedException {
        redisLock();
        Thread.sleep(100000);
    }

    private static void redisLock() throws InterruptedException{
//        RedissonManager.init(); //初始化

        for (int i = 0; i < 2; i++) {
            Thread t = new Thread(new Runnable() {
                String key = "test123";
                @Override
                public void run() {
                    try {

                        DistributedRedisLock.acquire(key);

                        DistributedRedisLock.release(key);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
//                        DistributedRedisLock.release(key);
                    }
                }
            });
            t.start();
        }
    }
}
